package io.zerous.gravitation

import android.graphics.Color
import io.zerous.engine.*
import io.zerous.engine.math.*
import io.zerous.engine.ui.Rocker
import io.zerous.engine.utils.ZCamera

/**
 * Created by Zerous on 2018/9/23.
 */
class MainScreen : Screen {
    val rocker = Rocker(Vector2(Zex.graphics.height/4f, Zex.graphics.height - Zex.graphics.height/4f), Zex.graphics.height / 6f)
    lateinit var world : PhysicsWorld
    lateinit var p1: Particle
    lateinit var p2: Particle
    lateinit var p3: Particle
    lateinit var p4: Particle

    val al = 150f

    var first = true

    val debug = false
    val camera = ZCamera(Vector2(0f, 0f))


    override fun resume() {
        world = PhysicsWorld(camera)
        val m1 = (Math.random() * 1000f).toFloat() + 9000f
        val m2 = (Math.random() * 1000f).toFloat() + 9000f
        val m3 = (Math.random() * 1000f).toFloat() + 9000f
        val m4 = (Math.random() * 0.001f).toFloat()
        p1 = Particle(Vector2(0f,  -al * Math.sqrt(3.0).toFloat()), m1, Vector2(0f, -20f) / m1)
        p2 = Particle(Vector2(al, 0f), m2, Vector2(0f, 10f) / m2)
        p3 = Particle(Vector2(-al, 0f), m3, Vector2(0f, 10f) / m3)
        p4 = Particle(Vector2(-2*al, -2*al), m4, Vector2(-10f, 10f))
        world.addParticle(p1)
        world.addParticle(p2)
        world.addParticle(p3)
        world.addParticle(p4)
    }

    override fun pause() {
        world.particles.clear()
    }

    override fun update(deltaTime: Float) {
        //rocker.update()

        //particle.addForce(rocker.getDirection())
        world.pUpdate()
    }

    override fun render() {
        if (first && debug) {
            Zex.graphics.clear(Color.WHITE)
            first = false
        } else {
            Zex.graphics.clear(Color.WHITE)
        }

        when(TRACK) {
            1 -> camera.position.set(p1.position)
            2 -> camera.position.set(p2.position)
            3 -> camera.position.set(p3.position)
            4 -> camera.position.set(p4.position)
        }

        world.draw()

        if (DEBUG) {
            Zex.graphics.drawText("m1:${p1.mass}", 0f, Zex.graphics.defaultFontSize + 1, Color.RED, TextAlign.LEFT)
            Zex.graphics.drawText("m2:${p2.mass}", 0f, Zex.graphics.defaultFontSize * 2 + 2, Color.GREEN, TextAlign.LEFT)
            Zex.graphics.drawText("m3:${p3.mass}", 0f, Zex.graphics.defaultFontSize * 3 + 3, Color.BLUE, TextAlign.LEFT)
            Zex.graphics.drawText("m4:${p4.mass}", 0f, Zex.graphics.defaultFontSize * 4 + 4, align = TextAlign.LEFT)

            Zex.graphics.drawLineWithZCamera(p4.position, p4.acceleration * 10f, Color.RED, camera)
            Zex.graphics.drawLineWithZCamera(p4.position, p4.velocity * 10f, Color.MAGENTA, camera)
        }
        world.update()
    }
}